
package com.joolun.cloud.mall.api.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.joolun.cloud.common.core.constant.CommonConstants;
import com.joolun.cloud.mall.api.mapper.DistributionConfigMapper;
import com.joolun.cloud.mall.api.mapper.UserInfoMapper;
import com.joolun.cloud.mall.api.service.DistributionConfigService;
import com.joolun.cloud.mall.common.constant.MallConstants;
import com.joolun.cloud.mall.common.entity.DistributionConfig;
import com.joolun.cloud.mall.common.entity.UserInfo;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 分销设置
 *
 * @author www.joolun.com
 * @date 2021-04-13 15:21:00
 */
@Service
@AllArgsConstructor
public class DistributionConfigServiceImpl extends ServiceImpl<DistributionConfigMapper, DistributionConfig> implements DistributionConfigService {

	private final UserInfoMapper userInfoMapper;
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void parentBind(String userType, UserInfo userInfo) {
		if(StrUtil.isNotBlank(userInfo.getSharerUserCode())){
			//获取分销配置
			DistributionConfig distributionConfig = baseMapper.selectOne(Wrappers.emptyWrapper());
			if(distributionConfig != null && CommonConstants.YES.equals(distributionConfig.getEnable())){//分销开启才往下走
				//获取当前用户信息
				UserInfo userInfo2 = userInfoMapper.selectById(userInfo.getId());
				if(StrUtil.isBlank(userInfo2.getParentId())){//没有上级ID的用户才往下走
					String bindType = distributionConfig.getBindType();
					//销关系绑定为所有用户或分销关系绑定为新用户且当前用户为新用户  才往下走
					if(MallConstants.DISTRIBUTION_BINDTYPE_1.equals(bindType) ||
							(MallConstants.DISTRIBUTION_BINDTYPE_2.equals(bindType) && DistributionConfigService.USER_TYPE_2.equals(userType))){
						//获取分享人的用户信息
						UserInfo userInfo3 = userInfoMapper.selectOne(Wrappers.<UserInfo>query().lambda()
								.eq(UserInfo::getUserCode, userInfo.getSharerUserCode()));
						if(userInfo3 != null && !userInfo3.getId().equals(userInfo.getId())){
							//设置当前用户的上级
							userInfo2.setParentId(userInfo3.getId());
							userInfoMapper.updateById(userInfo2);
						}
					}
				}
			}
		}
	}
}
